﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sofire.Data;

namespace SofireXSqlEntityGenerator.UI
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;
            this.InitControls();
        }

        private void InitControls()
        {
            combo_DatabaseProvider.Items.AddRange(Enum.GetNames(typeof(QueryEngineProvider)));
            combo_DatabaseProvider.DataBindings.Add("SelectedIndex", Properties.Settings.Default, "DatabaseProvider");
            txt_ConnectionString.DataBindings.Add("Text", Properties.Settings.Default, "ConnectionString");
        }

        private QueryEngineProvider SelectedProvider
        {
            get
            {
                return (QueryEngineProvider)combo_DatabaseProvider.SelectedIndex;
            }
        }

        private void btn_ConnectionSetting_Click(object sender, EventArgs e)
        {
           

        }

        private void btn_Login_Click(object sender, EventArgs e)
        {
            var provider = this.SelectedProvider;
            switch(provider)
            {
                case QueryEngineProvider.Microsoft_SQL_Server:
                case QueryEngineProvider.Oracle:
                case QueryEngineProvider.SQLite:
                    break;
                default:
                    this.ShowError("当前版本仅支持对 ORACLE/SQLite 数据库的支持！");
                    break;
            }

            if(txt_ConnectionString.TextLength == 0)
            {
                this.ShowError("请输入连接字符串！");
                return;
            }
            var engine = VSEx.CreateEngine(provider, txt_ConnectionString.Text);
            if(engine == null)
            {
                this.ShowError("当前版本不支持 " + this.SelectedProvider + "！");
                return;
            }
            if(this.IsSuccess(engine.TestConnection()))
            {
                this._Engine = engine;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                Properties.Settings.Default.Save();
                this.Close();
            }
        }

        private QueryEngineBase _Engine;
        public QueryEngineBase Engine
        {
            get
            {
                return this._Engine;
            }
        }

    }
}
